package myrecyclerview

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

abstract class BaseAdapter<T, B : ViewBinding> : RecyclerView.Adapter<BaseAdapter<T, B>.Holder>() {

    protected val TAG = javaClass.simpleName
    protected var mData: MutableList<T> = mutableListOf()
    protected var mWidth: Int = -1

    // 在适配器中
    override fun setHasStableIds(hasStableIds: Boolean) {
        super.setHasStableIds(true)
    }

    override fun getItemId(position: Int): Long {
        // 返回唯一稳定的ID，如数据库ID等
        return position.toLong()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val inflater = LayoutInflater.from(parent.context)
        return Holder(getB(inflater, parent))
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        bindHolder(holder, position)
    }

    abstract fun getB(inflater: LayoutInflater, parent: ViewGroup): B

    abstract fun bindHolder(holder: Holder, position: Int)

    fun getData(position: Int): T {
        return mData[position]
    }

    var data: MutableList<T>
        get() = mData
        set(data) {
            mData.clear()
            mData.addAll(data)
            notifyDataSetChanged()
        }

    fun addData(data: MutableList<T>) {
        mData.addAll(data)
        notifyItemRangeInserted((mData.size - data.size), data.size)
    }

    fun insertData(data: T?) {
        if (data == null) return
        mData.add(data)
        notifyItemInserted(itemCount - 1)
    }

    fun removeData(position: Int) {
        mData.removeAt(position)
        notifyItemRemoved(position)
    }

    fun clear() {
        mData.clear()
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    inner class Holder(itemView: B) : RecyclerView.ViewHolder(itemView.root) {
        var binding: B = itemView

        init {
            addEventListener(this)
        }
    }

    abstract fun addEventListener(holder: Holder)
}